package com.example.tools.security.handler;

import cn.hutool.json.JSONUtil;
import com.example.mallcommon.RestResult;
import com.example.mallcommon.constant.ResultCodeEnum;
import com.example.mallcommon.utils.WebUtils;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义返回结果：没有权限访问时
 * @Author: yang
 * @Date: 2021/8/22 0022 14:16
 * @Version 0.0.1
 */
@Component
public class MallAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
        String resBody= JSONUtil.toJsonStr(RestResult.custom(ResultCodeEnum.USER_ACCESS_UNAUTHORIZED));
        WebUtils.writeJson(httpServletResponse,resBody);
    }
}
